package com.haikesi.api.typetemplate.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.haikesi.api.base.Constants;
import com.haikesi.api.base.Type;
import com.haikesi.api.base.User;
import com.haikesi.api.typetemplate.dao.TypeTemplateMapper;
import com.haikesi.api.typetemplate.domain.po.TypeTemplatePO;
import com.haikesi.api.typetemplate.domain.vo.TypeTemplateBuyVO;
import com.haikesi.api.typetemplate.domain.vo.TypeTemplateSearchVO;
import com.haikesi.api.typetemplate.domain.vo.TypeTemplateUpDeVO;
import com.haikesi.api.typetemplate.domain.vo.TypeTemplateVO;
import com.haikesi.api.typetemplate.service.ITypeTemplateService;
import com.haikesi.exception.BusinessException;
import com.haikesi.util.ApcosApiUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class TypeTemplateServiceImpl implements ITypeTemplateService {

    @Autowired
    private TypeTemplateMapper dao;

    @Override
    public List<TypeTemplateVO> getList(TypeTemplateSearchVO typeTemplateSearchVO) {
        // 获取远程模板list
        String template = ApcosApiUtils.getTemplate(typeTemplateSearchVO.getTypeId(), "");
        JSONArray jsonArray = (JSONArray) JSONObject.parseArray(template);
        List<TypeTemplateVO> tempLateList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            TypeTemplateVO typeTemplateVO = new TypeTemplateVO();
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            jsonObject.put("templateName", jsonObject.get("template_name"));
            jsonObject.put("templateSign", jsonObject.get("id"));
            jsonObject.put("templateImage", jsonObject.get("template_thumbnail"));
//            jsonObject.put("templateImage", "../images/img-slide-5.jpg");
            jsonObject.put("remarks", "1");
            TypeTemplateVO typeTemplateVO1 = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), TypeTemplateVO.class);
            tempLateList.add(typeTemplateVO1);
        }

        List<TypeTemplateVO> locaTemplate = this.getTemplateList(typeTemplateSearchVO);
        /*for (int i = 0; i < locaTemplate.size(); i++) {
            if("1".equals(locaTemplate.get(i).getTemplateIsCommon())){
                locaTemplate.remove(locaTemplate.get(i));
            }
        }*/

        // 存放本地模板唯一标识码
        List<String> list = new ArrayList<>();
        for (int i = 0; i < locaTemplate.size(); i++) {
            list.add(locaTemplate.get(i).getTemplateSign());
        }

        // 判断模板否是本地存在，没有就添加到list里面。
        for (int i = 0; i < tempLateList.size(); i++) {
            if (!list.contains(tempLateList.get(i).getId())) {
                locaTemplate.add(tempLateList.get(i));
            }
        }

        return locaTemplate;
    }

    @Override
    public TypeTemplateVO getDefaultTemp(String typeId) {
        TypeTemplateSearchVO typeTemplateSearchVO = new TypeTemplateSearchVO();
        typeTemplateSearchVO.setTypeId(typeId);
//        typeTemplateSearchVO.setIsScreenOrganization("1");
        typeTemplateSearchVO.setTemplateDefault(1);
        List<TypeTemplateVO> list = this.getTemplateList(typeTemplateSearchVO);
        if (!list.isEmpty()) {
            return list.get(0);
        } else {
            throw new BusinessException(Type.EXCEPTION_FAIL);
        }
    }

    @Override
    public TypeTemplatePO buyTemp(TypeTemplateBuyVO buyVO) {
        //获取模板HTML代码
        String templateCode = ApcosApiUtils.getTemplateCode(buyVO.getTemplateSign());
        JSONObject jsonObject = JSON.parseObject(templateCode);
        buyVO.setTemplateCode(jsonObject.get("template_html").toString());

        //设置模板组织机构
        TypeTemplatePO po = new TypeTemplatePO();
        User user = po.getUser();
        if (user != null && user.getOrganizationId() != null) {
            buyVO.setOrganizationId(user.getOrganizationId());
        }
        buyVO.setTemplateDefault(false);
        BeanUtils.copyProperties(buyVO, po);
        po.preInsert();
        po.setId(UUID.randomUUID().toString());
        // 判断是否是PC模板
        if("1".equals(buyVO.getTemplateType())){
            po.setTemplateType(1);
        }else{
            po.setTemplateType(2);
        }
        int i = dao.insertSelective(po);
        if (i == Constants.SQL_RETUN_SUCCESS) {
            throw new BusinessException(Type.EXCEPTION_FAIL);
        }
        return po;
    }

    @Override
    public void updateDefaultTemp(TypeTemplateUpDeVO tempID) {
        String oldId = tempID.getOldId();
        String newId = tempID.getNewId();   //0000
        TypeTemplatePO po = new TypeTemplatePO();
        if("0000".equals(newId)){   //判断是否将通用模板设置为默认模板
            TypeTemplateSearchVO typeTemplateSearchVO = new TypeTemplateSearchVO();
            typeTemplateSearchVO.setTypeId(oldId);
            typeTemplateSearchVO.setTemplateDefault(1);
            List<TypeTemplateVO> list = this.getTemplateList(typeTemplateSearchVO);
            for (TypeTemplateVO vo : list) {
                if("1".equals(vo.getTemplateDefault())){
                    vo.setTemplateDefault("0");
                    po.setId(vo.getId());
                    po.setTemplateDefault(false);
                    dao.updateByPrimaryKeySelective(po);
                }
            }
        }else {
            po.setId(newId);
            po.setTemplateDefault(true);
            dao.updateByPrimaryKeySelective(po);
            if (!StringUtil.isEmpty(oldId)) {
                po.setId(oldId);
                po.setTemplateDefault(false);
                int i1 = dao.updateByPrimaryKeySelective(po);
            }
        }
    }


    //获取本地模板list
    public List<TypeTemplateVO> getTemplateList(TypeTemplateSearchVO typeTemplateSearchVO) {
        //当前用户没有组织机构就不需要带组织机构赛选功能
        TypeTemplatePO po = new TypeTemplatePO();
        User user = po.getUser();
        if (user == null) {
            typeTemplateSearchVO.setIsScreenOrganization("0");
        } else {
            if (user.getOrganizationId() != null) {
                //获取到最高级的组织机构ID
                String organizationId = dao.getOrganizationId(user.getOrganizationId());
                typeTemplateSearchVO.setOrganizationId(organizationId);
                typeTemplateSearchVO.setIsScreenOrganization("1");
            } else {
                typeTemplateSearchVO.setIsScreenOrganization("0");
            }
        }

        List<TypeTemplateVO> locaTemplate = dao.getListByTypeId(typeTemplateSearchVO);
        if (locaTemplate.size() < 1) {
            typeTemplateSearchVO.setIsScreenOrganization(null);
            typeTemplateSearchVO.setTemplateIsCommon(1);
            //获取通用模板
            locaTemplate = dao.getCommonTemp(typeTemplateSearchVO);
            if (!locaTemplate.isEmpty()) {
                locaTemplate.get(0).setTemplateDefault("1");
            } else {
                throw new BusinessException(Type.EXCEPTION_FAIL);
            }
        }
        return locaTemplate;
    }
}
